using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using RAG.Application.Dtos.Auth;
using RAG.Application.Services.Interfaces;
using RAG.Domain.Entities.App;
using RAG.Domain.Repositories;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using RAG.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace RAG.Application.Services.Implementations;

public class AuthService : IAuthService
{
    private readonly IRepository<Users> _userRepository;
    private readonly RagAIDbContext _context;
    private readonly IConfiguration _configuration;

    public AuthService(IRepository<Users> userRepository, RagAIDbContext context, IConfiguration configuration)
    {
        _userRepository = userRepository;
        _context = context;
        _configuration = configuration;
    }

    public async Task<AuthResponse> Login(UserLogin userLogin)
    {
        try
        {
            var users = await _userRepository.GetAllAsync();
            var user = users.FirstOrDefault(u => u.UserName == userLogin.Username);

            if (user == null)
            {
                return new AuthResponse
                {
                    Success = false,
                    Message = "用户名或密码错误"
                };
            }

            // 这里应该验证密码，暂时简化处理
            if (user.Password != userLogin.Password)
            {
                return new AuthResponse
                {
                    Success = false,
                    Message = "用户名或密码错误"
                };
            }

            // 获取用户的角色信息
            var userWithRoles = await _context.Users
                .Include(u => u.Roles)
                .FirstOrDefaultAsync(u => u.Id == user.Id);

            var userInfo = new UserInfo
            {
                Id = user.Id,
                Username = user.UserName,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                AvatarUrl = user.AvatarUrl,
                Status = user.Status,
                Roles = userWithRoles?.Roles.Select(r => r.RoleName).ToList() ?? new List<string>(),
                RoleTypes = userWithRoles?.Roles.Select(r => r.RoleType).ToList() ?? new List<string>()
            };

            // 生成JWT token
            var token = GenerateJwtToken(user, userWithRoles?.Roles.ToList() ?? new List<Roles>());

            return new AuthResponse
            {
                Success = true,
                Message = "登录成功",
                Token = token,
                UserInfo = userInfo
            };
        }
        catch (Exception ex)
        {
            return new AuthResponse
            {
                Success = false,
                Message = $"登录失败: {ex.Message}"
            };
        }
    }

    public async Task<AuthResponse> Register(UserRegister userRegister)
    {
        try
        {
            // 检查用户名是否已存在
            var existingUserByUsername = await _context.Users
                .FirstOrDefaultAsync(u => u.UserName == userRegister.Username);
            
            if (existingUserByUsername != null)
            {
                return new AuthResponse
                {
                    Success = false,
                    Message = "用户名已存在"
                };
            }

            // 检查邮箱是否已存在
            var existingUserByEmail = await _context.Users
                .FirstOrDefaultAsync(u => u.Email == userRegister.Email);
            
            if (existingUserByEmail != null)
            {
                return new AuthResponse
                {
                    Success = false,
                    Message = "邮箱已被注册"
                };
            }

            // 创建新用户
            var newUser = new Users
            {
                Id = Guid.NewGuid(),
                UserName = userRegister.Username,
                Password = userRegister.Password, // 实际应用中应该加密
                Email = userRegister.Email,
                PhoneNumber = userRegister.PhoneNumber,
                Status = "active",
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            // 保存用户
            await _userRepository.CreatedAsync(newUser);

            // 获取或创建"普通用户"角色
            var userRole = await GetOrCreateUserRole();

            // 为用户分配"普通用户"角色
            newUser.Roles.Add(userRole);
            await _context.SaveChangesAsync();

            // 创建用户信息
            var userInfo = new UserInfo
            {
                Id = newUser.Id,
                Username = newUser.UserName,
                Email = newUser.Email,
                PhoneNumber = newUser.PhoneNumber,
                AvatarUrl = newUser.AvatarUrl,
                Status = newUser.Status,
                Roles = new List<string> { "普通用户" },
                RoleTypes = new List<string> { "user" } // 普通用户的角色类型
            };

            return new AuthResponse
            {
                Success = true,
                Message = "注册成功，已自动分配普通用户角色",
                UserInfo = userInfo
            };
        }
        catch (Exception ex)
        {
            return new AuthResponse
            {
                Success = false,
                Message = $"注册失败: {ex.Message}"
            };
        }
    }

    /// <summary>
    /// 生成JWT Token
    /// </summary>
    private string GenerateJwtToken(Users user, List<Roles> roles)
    {
        var jwtSettings = _configuration.GetSection("JwtSettings");
        var secretKey = jwtSettings["SecretKey"] ?? throw new InvalidOperationException("JWT SecretKey not configured");
        var issuer = jwtSettings["Issuer"] ?? "RAG.AI";
        var audience = jwtSettings["Audience"] ?? "RAG.AI.Users";
        var expirationInMinutes = int.Parse(jwtSettings["ExpirationInMinutes"] ?? "60");

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.Email, user.Email)
        };

        // 添加角色声明
        foreach (var role in roles)
        {
            claims.Add(new Claim(ClaimTypes.Role, role.RoleName));
        }

        var token = new JwtSecurityToken(
            issuer: issuer,
            audience: audience,
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(expirationInMinutes),
            signingCredentials: credentials
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    /// <summary>
    /// 获取或创建"普通用户"角色
    /// </summary>
    private async Task<Roles> GetOrCreateUserRole()
    {
        var userRole = await _context.Roles
            .FirstOrDefaultAsync(r => r.RoleName == "普通用户");

        if (userRole == null)
        {
            // 创建"普通用户"角色
            userRole = new Roles
            {
                Id = Guid.NewGuid(),
                RoleName = "普通用户",
                Description = "系统默认的普通用户角色",
                RoleType = "user",
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _context.Roles.AddAsync(userRole);
            await _context.SaveChangesAsync();
        }

        return userRole;
    }
}